<template>
  <div class="new-contact-list">
    <!-- 操作栏 -->
    <el-row justify="end">
      <el-button
        @click="openForm"
        type="primary"
        class="!bg-#ebecf0 !color-#42526b"
        style="border: none"
      >
        <Icon class="mr-5px" icon="ep:plus" />
        新增联系人
      </el-button>
      <el-button
        @click="openBusinessModal"
        v-hasPermi="['crm:contact:create-business']"
        v-if="queryParams.businessId"
      >
        <Icon class="mr-5px" icon="ep:circle-plus" />关联
      </el-button>
      <el-button
        @click="deleteContactBusinessList"
        v-hasPermi="['crm:contact:delete-business']"
        v-if="queryParams.businessId"
      >
        <Icon class="mr-5px" icon="ep:remove" />解除关联
      </el-button>
    </el-row>

    <!-- 列表 -->
    <ContentWrap class="contact mt-10px">
      <el-table
        border
        :header-cell-style="tableHeaderColor"
        ref="contactRef"
        v-loading="loading"
        :data="list"
        :stripe="true"
        @row-click="openDetail"
        :show-overflow-tooltip="true"
      >
        <el-table-column type="selection" width="55" v-if="queryParams.businessId" />
        <el-table-column label="姓名" fixed="left" align="center" prop="name">
          <template #default="scope">
            <span class="color-#0052cc cursor-pointer"> {{ scope.row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="手机" prop="encryptMobile" width="150">
          <template #default="scope">
            <div>
              <el-link v-if="scope.row.mobile" @click="onCall(scope.row, scope.row.mobile)"
                >{{ scope.row.encryptMobile }} <Icon class="ml-5px" icon="ep:phone" />
              </el-link>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="职位" align="center" prop="post" />
        <el-table-column label="直属上级" align="center" prop="parentName" />
        <el-table-column label="是否关键决策人" align="center" prop="master" min-width="100">
          <template #default="scope">
            <dict-tag :type="DICT_TYPE.INFRA_BOOLEAN_STRING" :value="scope.row.master" />
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <!-- <Pagination
        :total="total"
        v-model:page="queryParams.pageNo"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      /> -->
      <div
        class="color-#0052cc text-14px text-center mt-10px"
        style="cursor: pointer"
        v-if="!isMore"
      >
        <div @click="pageNext">
          <div>加载更多</div>
          <svg
            t="1742280566606"
            class="icon"
            viewBox="0 0 1024 1024"
            version="1.1"
            xmlns="http://www.w3.org/2000/svg"
            p-id="1500"
            width="20"
            height="20"
          >
            <path
              d="M794.819048 502.247619c9.752381 9.752381 9.752381 29.257143 0 39.009524l-258.438096 234.057143c-4.87619 4.87619-14.628571 9.752381-19.504762 9.752381-9.752381 0-14.628571-4.87619-19.504761-9.752381l-258.438096-234.057143c-4.87619-4.87619-9.752381-9.752381-9.752381-19.504762s4.87619-14.628571 9.752381-19.504762c14.628571-9.752381 29.257143-9.752381 43.885715 0l234.057142 214.552381 238.933334-214.552381c9.752381-9.752381 29.257143-9.752381 39.009524 0z m-9.752381-248.685714c9.752381 9.752381 9.752381 29.257143 0 39.009524l-258.438096 234.057142c-4.87619 4.87619-14.628571 9.752381-19.504761 9.752381-9.752381 0-14.628571-4.87619-19.504762-9.752381L229.180952 287.695238c-4.87619-4.87619-9.752381-9.752381-9.752381-19.504762s4.87619-14.628571 9.752381-19.504762c14.628571-9.752381 29.257143-9.752381 43.885715 0l234.057143 214.552381 234.057142-214.552381c14.628571-9.752381 29.257143-9.752381 43.885715 4.876191z"
              fill="#0052cc"
              p-id="1501"
            ></path>
          </svg>
        </div>
      </div>
      <div class="color-#6b778c text-14px text-center mt-10px" v-else>没有更多数据了</div>
    </ContentWrap>

    <!-- 表单弹窗：添加 -->
    <ContactForm ref="formRef" @success="handleQuery" />
    <!-- 关联商机选择弹框 -->
    <ContactListModal
      ref="contactModalRef"
      :customer-id="props.customerId"
      @success="createContactBusinessList"
      :is-width="false"
    />
    <!-- 详情弹窗 -->
    <CrmSpec ref="crmSpec" @getPage="handleQuery" />
  </div>
</template>
<script setup lang="ts">
import * as ContactApi from '@/api/crm/contact'
import ContactForm from './../ContactForm.vue'
import { DICT_TYPE } from '@/utils/dict'
import { BizTypeEnum } from '@/api/crm/permission'
import ContactListModal from './ContactListModal.vue'
import WebPhone from '@/hooks/web/useCall'
import { useSoftPhoneStore } from '@/store/modules/softPhone'
import { usePhoneStore } from '@/store/modules/phone'
import { emitter } from '@/utils/eventBus.ts'

const useStore = usePhoneStore()
const useSoftPhone = useSoftPhoneStore()
defineOptions({ name: 'CrmContactList' })
const props = defineProps<{
  bizType: number // 业务类型
  bizId: number // 业务编号
  customerId: number // 特殊：客户编号；在【商机】详情中，可以传递客户编号，默认新建的联系人关联到该客户
  businessId: number // 特殊：商机编号；在【商机】详情中，可以传递商机编号，默认新建的联系人关联到该商机
}>()

const loading = ref(true) // 列表的加载中
const total = ref(0) // 列表的总页数
const list = ref([]) // 列表的数据
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  customerId: undefined as unknown, // 允许 undefined + number
  businessId: undefined as unknown // 允许 undefined + number
})
const message = useMessage()

const isMore = computed(() => {
  if (list.value.length != total.value) {
    return false
  } else {
    return true
  }
})
/**下一页*/
const pageNext = async () => {
  queryParams.pageNo += 1
  loading.value = true
  try {
    let data = { list: [], total: 0 }
    switch (props.bizType) {
      case BizTypeEnum.CRM_CUSTOMER:
        queryParams.customerId = props.bizId
        data = await ContactApi.getContactPageByCustomer(queryParams)
        break
      case BizTypeEnum.CRM_BUSINESS:
        queryParams.businessId = props.bizId
        data = await ContactApi.getContactPageByBusiness(queryParams)
        break
      default:
        return
    }
    data.list.map((item) => {
      list.value.push(item)
    })
    total.value = data.total
  } finally {
    loading.value = false
  }
}
/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    // 置空参数
    queryParams.customerId = undefined
    // 执行查询
    let data = { list: [], total: 0 }
    switch (props.bizType) {
      case BizTypeEnum.CRM_CUSTOMER:
        queryParams.customerId = props.bizId
        data = await ContactApi.getContactPageByCustomer(queryParams)
        break
      case BizTypeEnum.CRM_BUSINESS:
        queryParams.businessId = props.bizId
        data = await ContactApi.getContactPageByBusiness(queryParams)
        break
      default:
        return
    }
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 获取路由带的参数 */
const { params } = useRoute()

/** 添加操作 */
const formRef = ref()
const openForm = () => {
  formRef.value.open('create', undefined, props.customerId, props.businessId, props.customerId)
}

/** 打开联系人详情 */
const { push } = useRouter()
const crmSpec = ref(null)
const openDetail = (row) => {
  const nowIds = list.value.map((item) => item.id)
  crmSpec.value.setDrawer(true, 'contact', row.id, nowIds)
}

/** 打开联系人与商机的关联弹窗 */
const contactModalRef = ref()
const openBusinessModal = () => {
  contactModalRef.value.open()
}
const createContactBusinessList = async (contactIds: number[]) => {
  const data = {
    businessId: props.bizId,
    contactIds: contactIds
  } as ContactApi.ContactBusiness2ReqVO
  contactRef.value.getSelectionRows().forEach((row: ContactApi.ContactVO) => {
    data.businessIds.push(row.id)
  })
  await ContactApi.createContactBusinessList2(data)
  // 刷新列表
  message.success('关联联系人成功')
  handleQuery()
}

/** 解除联系人与商机的关联 */
const contactRef = ref()
const deleteContactBusinessList = async () => {
  const data = {
    businessId: props.bizId,
    contactIds: contactRef.value.getSelectionRows().map((row: ContactApi.ContactVO) => row.id)
  } as ContactApi.ContactBusiness2ReqVO
  if (data.contactIds.length === 0) {
    return message.error('未选择联系人')
  }
  await ContactApi.deleteContactBusinessList2(data)
  // 刷新列表
  message.success('取关联系人成功')
  handleQuery()
}

/** 监听打开的 bizId + bizType，从而加载最新的列表 */
watch(
  () => [props.bizId, props.bizType],
  ([val, val2]) => {
    if (val && val2) handleQuery()
  },
  { immediate: true, deep: true }
)
// 更改表头颜色
const tableHeaderColor = () => {
  return { background: '#fff', color: '#6b778c' }
}

const onCall = (row, callee) => {
  emitter.emit('simCall', {
    callee,
    source: 'contact',
    sourceId: row.id
  })
  emitter.emit('userCallCallee', callee)
}
</script>
<style scoped>
.contact >>> .el-card__body {
  padding: 0;
}
.new-contact-list {
  background-color: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 8px #172b4d1a;
  margin: 0 8px;
  padding: 16px;
}
</style>
